package com.rub.android.ui.activity

import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.ExoPlayerFactory
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.trackselection.TrackSelection
import com.google.android.exoplayer2.trackselection.TrackSelector
import com.google.android.exoplayer2.ui.PlayerView
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory
import com.rub.android.R


/**
 * https://codingdict.com/sources/java/com.google.android.exoplayer/71915.html
 * https://www.jianshu.com/p/6e466e112877
 * https://blog.csdn.net/weixin_41010198/article/details/88055078
 */
class ExoPlayerActivity : AppCompatActivity() {

    private val url = "http://vjs.zencdn.net/v/oceans.mp4"

    //var player: SimpleExoPlayer? = null
    var playerView: PlayerView? = null
    private var player: ExoPlayer? = null
    private var playWhenReady = false
    private var currentWindow = 0
    private var playbackPosition: Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_exoplayer2)
        playerView = findViewById(R.id.video_view)
        initializePlayer()
    }

    private fun initializePlayer() {
        val videoTrackSelectionFactory: TrackSelection.Factory =
            AdaptiveTrackSelection.Factory(DefaultBandwidthMeter())

        val trackSelector: TrackSelector = DefaultTrackSelector(videoTrackSelectionFactory)
        player = ExoPlayerFactory.newSimpleInstance(this, trackSelector)

        playerView!!.player = player
        player!!.playWhenReady = playWhenReady
        player!!.seekTo(currentWindow, playbackPosition)

        //创建一个mp4媒体文件
        //val uri = Uri.parse(getString(R.string.media_url_mp4))
        val uri = Uri.parse(url)
        val mediaSource: MediaSource = buildMediaSource(uri)
        player?.prepare(mediaSource, true, false)
    }


    private fun buildMediaSource(uri: Uri): MediaSource {
        return ExtractorMediaSource.Factory(
            DefaultHttpDataSourceFactory("exoplayer-codelab")
        ).createMediaSource(uri)
    }

    override fun onDestroy() {
        super.onDestroy()
        releasePlayer()
    }

    private fun releasePlayer() {
        if (player != null) {
            playbackPosition = player!!.currentPosition
            currentWindow = player!!.currentWindowIndex
            playWhenReady = player!!.playWhenReady
            player!!.release()
            player = null
        }
    }
}